<template>
  <div>
    <div class="dr_content">
      <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" />
      <ZwTable ref="tableRef" class="table-box" :option="tableOption" :fetch-params="state.searchParams" :rowKey="getRowKey" :fetch-api="conversionList" @select="onSelect" @selection-change="onSelectionChange" @select-all="onSelectAll">
        <template #headerOperate>
          <el-button @click="handleAbandon" :type="checkList.length == 0 ? 'default' : 'primary'" :disabled="checkList.length == 0">批量放弃</el-button>
        </template>
      </ZwTable>
    </div>
    <!-- 放弃弹框 -->
    <Dialog :appDialog="abandonDialog">
      <div class="abandon">
        <div class="photo"><img src="@/assets/customer/warn.png" /></div>
        <div class="abandonstyle">
          <div style="margin-bottom: 16px">放弃线索后，线索将不能被员工认领、不能被公海分配和回收</div>
          <el-form :model="abandonData" label-width="auto">
            <el-form-item label="放弃原因" required>
              <el-select v-model="abandonData.invalid_id" placeholder="请选择放弃原因">
                <el-option :label="item.name" :value="item.id" v-for="(item, index) in reasonListData"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Dialog>
    <TransCustomer :open="isopenCustomer" :work_user_info="work_user_info" :seas_id="rowid" :title="title" :rowid="id" @close="isopenCustomer = false" @submit="reset"></TransCustomer>
  </div>
</template>
<script lang="tsx" setup>
  import { ref, reactive, computed, inject, onMounted } from 'vue'
  import { ElMessage, ElButton } from 'element-plus'
  import ZwTable from '@/components/zw/table/Table'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import { getClubLevel, conversionList, setAbandon, reasonList } from '@/api/customer/clubManage/commonSea'
  import { deepCopy } from '@/utils/helper'
  import TransCustomer from './TransCustomer.vue'
  import Dialog from '@/components/Dialog.vue'

  const isShow = ref(0)
  const reasonListData = reactive([])
  const abandonData = reactive({ invalid_id: '' })
  const checkList = ref([])
  const emit = defineEmits(['close'])
  const rowid = inject('rowid')
  const defaultParams = {
    clue_seas_id: rowid.value,
    clue_type: 1 //线索类型：1未转化，2已转化，3已放弃
  }
  const tableRef = ref<HTMLElement | null>(null)
  const isopen = ref(false)
  const id = ref(null) //行线索id
  let title = ref('') //流转记录抽屉标题
  let isopenCustomer = ref(false) //判断转化客户抽屉是否打开
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const clue_list_ids = reactive([])
  const work_user_info = reactive({
    id: undefined,
    name: undefined
  })

  const searchOption = computed(() => {
    return [
      {
        label: '执行员工',
        name: 'work_user_list',
        value: [],
        type: 'select',
        placeholder: '请选择执行员工',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        formatOption: (v: any) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '线索等级',
        name: 'clue_level_id',
        value: '',
        type: 'select',
        placeholder: '请选择线索等级',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            getClubLevel({ page: 1, page_size: 99 }).then((res: any) => {
              let levelid: any = []
              res.data.forEach((item: any) => {
                console.log(item)
                levelid.push(item)
                resolve(levelid)
              })
            })
          })
        },
        formatOption: (v: any) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '转化失败',
        name: 'conversion_status',
        value: '',
        type: 'select',
        placeholder: '请选择是否失败',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve([
                { name: '未转化', id: 2 },
                { name: '转化失败', id: 1 }
              ])
            }, 100)
          })
        },
        formatOption: (v: any) => ({
          label: v.name,
          value: v.id
        })
      }
    ]
  })
  let tableOption = [
    {
      type: 'selection',
      width: 55,
      fixed: 'left',
      reserveSelection: true
    },
    {
      prop: 'mobile',
      label: '手机号',
      width: 160
    },
    {
      prop: 'clue_name',
      label: '线索名称',
      showOverflowTooltip: true,
      width: 140
    },
    {
      prop: 'clue_level_name',
      label: '线索等级',
      width: 160
    },
    {
      prop: 'operation_msg',
      label: '失败原因',
      showOverflowTooltip: true,
      width: 140
    },
    {
      prop: 'operation_time',
      width: 220,
      label: '转化时间'
    },
    {
      prop: 'operation_user_name',
      label: '执行人'
    },
    {
      prop: 'operate',
      label: '操作',
      width: 200,
      fixed: 'right',
      isOperate: true,
      renderOperate({ row }) {
        return (
          <>
            <ElButton
              class="table-button"
              size="small"
              onClick={() => {
                id.value = row.id
                title.value = `【${row.clue_name}】转化为客户`
                isopenCustomer.value = true
              }}
            >
              转化为客户
            </ElButton>
            <ElButton
              class="table-button"
              size="small"
              onClick={() => {
                onChange(1)
                clue_list_ids.splice(0, clue_list_ids.length, row.id)
                work_user_info.id = row.work_user_id
                work_user_info.name = row.work_user_name
                id.value = row.id
              }}
            >
              放弃
            </ElButton>
          </>
        )
      }
    }
  ]

  const close = () => {
    emit('close')
  }
  const getRowKey = (row: any) => {
    return row.id
  }
  //查询
  const search = (v) => {
    tableRef.value.getTable().clearSelection()
    Object.assign(state.searchParams, v)
  }
  //清空
  const reset = () => {
    tableRef.value.getTable().clearSelection()
    state.searchParams = deepCopy(defaultParams)
  }
  // 选中表格 checkbox
  const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map((v) => v.id)
  }
  // 选择项变更
  const onSelectionChange = (selection) => {
    console.log(selection)
  }
  // 全选
  const onSelectAll = (selection) => {
    checkList.value = selection.map((v) => v.id)
  }
  const onChange = (num: number) => {
    switch (num) {
      case 0:
        abandonDialog.title = '批量放弃提醒'
        abandonDialog.content = '确认放弃所选内容吗？'
        break
      case 1:
        abandonDialog.title = '放弃提醒'
        abandonDialog.content = '确认放弃所选内容吗？'
        break
    }
    isShow.value = num
    abandonDialog.visible = true
  }

  //获取放弃原因列表
  const getReasonList = () => {
    reasonList({ page: 1, page_size: 99 }).then((res: any) => {
      const data: Array<any> = res.data || []
      reasonListData.splice(0, reasonListData.length, ...data)
    })
  }

  // 批量放弃
  const handleAbandon = () => {
    onChange(0)
    clue_list_ids.splice(0, clue_list_ids.length, ...checkList.value)
  }

  // 放弃
  const submitAbandon = () => {
    if (!abandonData.invalid_id) {
      ElMessage.warning('请选择放弃原因')
      return
    }
    setAbandon({ clue_list: clue_list_ids, invalid_id: abandonData.invalid_id }).then((res) => {
      abandonDialog.visible = false
      ElMessage.success('放弃成功')
      reset()
    })
  }
  const cancelAbandon = () => {
    abandonDialog.visible = false
  }
  const abandonDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '500px',
    cancel: cancelAbandon,
    submit: submitAbandon,
    cancelText: '取消',
    submitText: '确定'
  })

  onMounted(() => {
    getReasonList()
  })
</script>
<style scoped lang="scss">
  .content {
    padding: 16px 0;
    height: calc(100vh - 100px) !important;
    overflow: auto;
  }
  .table-button {
    padding: 0;
  }
  .abandon {
    display: flex;
    padding: 33px 0;
    img {
      width: 36px;
      height: 36px;
    }
    .photo {
      display: flex;
      align-items: center;
      margin-right: 5px;
    }
    .abandonstyle {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      :deep .el-form-item {
        margin-bottom: 0px;
      }
    }
  }
</style>
